package es.mgil.cordova.plugins;

import org.apache.cordova.api.CallbackContext;
import org.apache.cordova.api.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;

import android.content.Intent;
import android.net.Uri;

/**
 * Plugin para visualizar una imagen dada su URL o Path
 * 
 * @author marc
 */
public class ImageView extends CordovaPlugin {
	private static final int VIEW_IMAGE = 1;
	private CallbackContext cbContext;

	@Override
	public boolean execute(String action, JSONArray args,
			CallbackContext callbackContext) throws JSONException {
		this.cbContext = callbackContext;
		startImageActivity(args.getString(0));
		return true;
	}

	public void startImageActivity(String imagePath) {
		Intent intent = new Intent();
		intent.setAction(Intent.ACTION_VIEW);
		intent.setDataAndType(Uri.parse(imagePath), "image/*");
		cordova.startActivityForResult(this, intent, VIEW_IMAGE);
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent intent) {
		if (resultCode == 0) {
			switch (requestCode) {
			case (VIEW_IMAGE):
				this.cbContext.success();
				break;
			default:
				this.cbContext.error("Algo ha ido mal al mostrar la imagen");
				break;
			}
		} else {
			this.cbContext.error("No existe la imagen");
		}

		super.onActivityResult(requestCode, resultCode, intent);
	}
}